package BlockingQueue_12;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.BlockingQueue;
public class 限流系统_SynchronousQueue {
    public static void main(String[] args) {
        final int THREAD_COUNT = 15;
        final BlockingQueue<Object> limiter = new SynchronousQueue<>(true); // 公平模式

        // 限流控制器线程
        new Thread(new Runnable() {
            public void run() {
                try {
                    while (true) {
                        // 每500毫秒放行一个请求
                        Thread.sleep(500);
                        limiter.put(new Object()); // 放入一个令牌
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "限流控制器").start();

        // 工作线程
        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        while (true) {
                            System.out.println("线程 " + threadId + " 等待限流通行");
                            limiter.take(); // 获取令牌
                            System.out.println("线程 " + threadId + " 获得通行，开始处理");
                            Thread.sleep((long)(Math.random() * 300)); // 模拟处理时间
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "工作线程-" + i).start();
        }
    }
}